package com.xw.studyone

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.xw.studyone.databinding.ActivityMainBinding
import com.xw.studyone.progress.MyService
import com.xw.studyone.progress.MyService2


class MainActivity : AppCompatActivity() {

    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    private var myService: IMyService? = null
    private var isBound: Boolean = false

    private val clientMessenger  by lazy { Messenger(ReturnHandler()) }
    private lateinit var mMessenger: Messenger
    private val downloadListener by lazy { OnDownLoadListener() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        val intent = Intent(this,MyService::class.java)
        bindService(intent,connection,Context.BIND_AUTO_CREATE)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent)
        } else {
            startService(intent)
        }

        val intent2 = Intent(this, MyService2::class.java)
        bindService(intent2,connection2,Context.BIND_AUTO_CREATE)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent2)
        } else {
            startService(intent2)
        }

        binding.btnStart.setOnClickListener {
            myService?.start("https://www.baidu.com")
        }

        binding.btnPause.setOnClickListener {
            myService?.pause()
        }

        binding.btnClose.setOnClickListener {
            myService?.close()
        }

        binding.btnBinder.setOnClickListener {
            val msg = Message.obtain(null,0)
            val bundle = Bundle()
            bundle.putString("type","这是activity发送的测试数据")
            msg.data = bundle
            msg.replyTo = clientMessenger

            mMessenger.send(msg)
        }
    }

    private val connection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            //以下是aidl 实现的方法
            // 通过 Stub.asInterface() 获取 Proxy 对象
            myService = IMyService.Stub.asInterface(service)
            isBound = true
            regiseterServiceListener()
        }

        override fun onServiceDisconnected(name: ComponentName) {
            isBound = false
            unregiseterServiceListener()
        }
    }

    private fun unregiseterServiceListener() {
        myService?.unregisterOnDownloadListener(downloadListener)
    }

    private fun regiseterServiceListener() {
        myService?.registerOnDownloadListener(downloadListener)
    }

    private inner class OnDownLoadListener: IDownLoadListener.Stub() {
        override fun onStateChange(state: Int) {
            Log.d("info", "======下载状态=====$state")
        }

        override fun onProgressChange(progress: Int) {
            Log.d("info", "======下载进度状态=====$progress")
        }

    }

    private val connection2: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            //以下是binder 实现的方法
            mMessenger  = Messenger(service)
        }

        override fun onServiceDisconnected(name: ComponentName) {
            isBound = false
        }
    }

    /*********************Binder**********************/
    inner class ReturnHandler: Handler(Looper.getMainLooper()) {

        override fun handleMessage(msg: Message) {
            when(msg.what) {

                1 -> {

                    val bundle = msg.data
                    if (bundle != null) {

                        val result = bundle.getString("kep")
                        Log.d("info","=====接收到服务发送过来的消息===" + result)
                    }
                }

                 else ->   super.handleMessage(msg)
            }
        }
    }

    override fun onStop() {
        super.onStop()

        unbindService(connection)
    }
}